package com.androiddelphi;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Toast;

public class Splash extends Activity {

	private int timer = 0;
	String NomeBancoDados = "RegistrarAPP";
	Cursor cursor = null;
	String nome = null;
	String registrado = "1";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		CriarTabela();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		Thread thread = new Thread(){
			
			@Override
			public void run() {
				
				while(timer < 3000){
					try{
						sleep(500);
						timer += 500;
					}catch(InterruptedException e){
						e.printStackTrace();
					}
				}
				timer = 0;
				if(registrado == "1"){
					Intent i = new Intent(Splash.this, Principal.class);
					startActivity(i);
				}else{
					Intent i = new Intent(Splash.this, RegistrarAPP.class);
					startActivity(i);
				}
			}
		};
		thread.start();
	}

	private void CriarTabela() {
		// TODO Auto-generated method stub
		SQLiteDatabase db = null;
		try {
			db = openOrCreateDatabase(NomeBancoDados, Context.MODE_PRIVATE,
					null);
			StringBuilder sql = new StringBuilder();
			sql.append("CREATE TABLE IF NOT EXISTS registroAPP(");
			sql.append("_id integer Primary key autoincrement,");
			sql.append("nome varchar (120),");
			sql.append("telefone varchar (19),");
			sql.append("email varchar (100))");
			db.execSQL(sql.toString());
			Toast.makeText(getApplicationContext(), "Tabela ja criada",
					Toast.LENGTH_SHORT).show();
			// VerificaCadastro();
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(getApplicationContext(), "Erro ocorreu",
					Toast.LENGTH_SHORT).show();
		} finally {
			db.close();
		}

	}

	public String VerificaCadastro(String cadastrado) {
		SQLiteDatabase db = null;
		try {
			db = openOrCreateDatabase(NomeBancoDados, MODE_PRIVATE, null);
			cursor = db.rawQuery("select * from registroAPP ", null);
			cursor.moveToNext();
			nome = cursor.getString(cursor.getColumnIndex("nome"));
			cadastrado = "1";
			// run();

		} catch (Exception e) {
			mensagemAlerta("BANCO DE DADOS",
					"Erro abrindo " + nome + " " + e.getMessage());
			cadastrado = "0";

		} finally {
			db.close();
		}
		return cadastrado;

	}

	public void mensagemAlerta(String tituloAlerta, String mensagemAlerta) {

		AlertDialog.Builder mensagem = new AlertDialog.Builder(Splash.this);

		mensagem.setTitle(tituloAlerta);
		mensagem.setMessage(mensagemAlerta);
		mensagem.setNeutralButton("OK", null);
		mensagem.show();
	}

}
